//
//  LOTimer.swift
//  HighScoreTalk
//
//  Created by apple on 16/2/5.
//  Copyright © 2016年 apple. All rights reserved.
//

import Foundation 
class LOTimer {
    var interval:Double=0
    var time:Double = 10000
    var handler:(LOTimer)->Void = {_ in
        
    }
    
    var onStart:()->Void = {}
    var onStop:()->Void = {}
    private var timer:dispatch_source_t?
    
    var startTime:NSTimeInterval = NSDate().timeIntervalSince1970
    var currentTime:NSTimeInterval {
        get{
            return NSDate().timeIntervalSince1970 - startTime
        }
    }
    
    convenience init(interval:Double,handler:(LOTimer)->Void) {
        self.init(interval: interval, time: 1000, handler: handler)
    }
    
    init(interval:Double,time:Double,handler:(LOTimer)->Void) {
        self.interval = interval
        self.handler = handler
        self.time = time
        let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue)
        let num:Double = self.interval * Double(NSEC_PER_SEC)
        dispatch_source_set_timer(self.timer!, dispatch_walltime(nil, 0),UInt64(num), 0)
        dispatch_source_set_event_handler(self.timer!, handler2)
    }
    
    
    func handler2() {
        handler(self)
        if self.currentTime >= self.time {
            self.stop()
        }
    }
    
    static func timer(interval:Double,time:Double,handler:(LOTimer)->Void)->LOTimer {
        let timer:LOTimer = LOTimer(interval: interval,time:time, handler: handler)
        timer.start()
        return timer
    }
    
    func cancel(){
        dispatch_suspend(self.timer!)
    }
    
    func start()
    {
        startTime = NSDate().timeIntervalSince1970
        dispatch_resume(self.timer!)
        self.onStart()
    }
    
    func stop()
    {
        dispatch_suspend(self.timer!)
        self.onStop()
    }
}